import { NextRequest, NextResponse } from 'next/server';
import { ContentGenerationRequest, ContentGenerationResponse } from '@/types';
import { contentGenerator } from '@/lib/content-generator';

export async function POST(request: NextRequest) {
  try {
    // 解析请求体
    const body: ContentGenerationRequest = await request.json();
    
    // 验证请求参数
    const validationError = validateRequest(body);
    if (validationError) {
      return NextResponse.json(
        { error: validationError },
        { status: 400 }
      );
    }

    // 生成多平台内容
    const result: ContentGenerationResponse = await contentGenerator.generateMultiPlatformContent(body);
    
    // 返回结果
    return NextResponse.json(result);

  } catch (error) {
    console.error('API处理错误:', error);
    
    return NextResponse.json(
      { 
        error: '内容生成失败，请稍后重试',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}

export async function GET() {
  return NextResponse.json({
    message: '文案生成API',
    endpoints: {
      POST: '/api/generate - 生成多平台文案',
    },
    supportedPlatforms: [
      'douyin', 'toutiao', 'xiaohongshu', 'csdn', 'juejin', 
      'kuaishou', 'weibo', 'baidu', 'shopee', 'tieba', 
      'segmentfault', 'douban', 'csdn_blog', 'wechat'
    ]
  });
}

/**
 * 验证请求参数
 */
function validateRequest(body: ContentGenerationRequest): string | null {
  if (!body.originalContent) {
    return '请提供原始内容';
  }

  if (typeof body.originalContent !== 'string') {
    return '原始内容必须是字符串';
  }

  if (body.originalContent.trim().length === 0) {
    return '原始内容不能为空';
  }

  if (body.originalContent.length > 10000) {
    return '原始内容长度不能超过10000字符';
  }

  if (!Array.isArray(body.selectedPlatforms)) {
    return '平台选择必须是数组';
  }

  if (body.selectedPlatforms.length === 0) {
    return '请至少选择一个平台';
  }

  if (body.selectedPlatforms.length > 14) {
    return '最多只能选择14个平台';
  }

  // 验证平台ID的有效性
  const validPlatforms = [
    'douyin', 'toutiao', 'xiaohongshu', 'csdn', 'juejin', 
    'kuaishou', 'weibo', 'baidu', 'shopee', 'tieba', 
    'segmentfault', 'douban', 'csdn_blog', 'wechat'
  ];

  for (const platform of body.selectedPlatforms) {
    if (!validPlatforms.includes(platform)) {
      return `无效的平台ID: ${platform}`;
    }
  }

  return null;
}